﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace NasuTek.Shion
{
    class LineParser
    {
        public static string ParseToSpan(string line)
        {
            string returnval;
            returnval = ParseHTMLForSmell(line);
            //returnval = ParseHTML(returnval); //TODO: Fix this code
            returnval = ParseBold(returnval);
            returnval = ParseUnderline(returnval);
            returnval = ParseColors(returnval);
            returnval = SpanCleaner(returnval);
            return returnval;
        }

        static string SpanCleaner(string line)
        {
            string returnval = line;
            Regex addSpanAtEnd = new Regex(@"<span class=""(?<class>[^\s""]+)"">(?<actualText>[^<]+)");
            foreach (Match i in addSpanAtEnd.Matches(returnval))
            {
                returnval = returnval.Replace("<span class=\"" + i.Groups["class"] + "\">" + i.Groups["actualText"], "<span class=\"" + i.Groups["class"] + "\">" + i.Groups["actualText"] + "</span>");
            }
            return returnval;
        }

        static string ParseHTMLForSmell(string line)
        {
            string returnval = line;
            if (Form1.config.NoHTMLRenderingOutsideClient == true)
            {
                returnval = returnval.Replace(">", "&gt;");
                returnval = returnval.Replace("<", "&lt;");
            }
            else
            {
                //Filter out functions that can be used to exploit the client
                returnval = returnval.Replace("<style>", "&lt;style&gt;");
                returnval = returnval.Replace("</style>", "&lt;/style&gt;");
                returnval = returnval.Replace("<script>", "&lt;script&gt;");
                returnval = returnval.Replace("</script>", "&lt;/script&gt;");
                returnval = returnval.Replace("<html>", "&lt;html&gt;");
                returnval = returnval.Replace("</html>", "&lt;/html&gt;");
                returnval = returnval.Replace("<body>", "&lt;body&gt;");
                returnval = returnval.Replace("</body>", "&lt;/body&gt;");
            }
            return returnval;
        }
        static string ParseBold(string line)
        {
            string returnval = line;
            bool enabled = false;
            string sample = "";

/*            foreach (char i in returnval.ToCharArray())
            {
                if (i == '')
                {
                    if (enabled) 
                    { 
                        enabled = false;
                        returnval = returnval.Replace(sample, "<strong>" + sample + "</strong>");
                        sample = "";
                    }
                    if (!enabled) { enabled = true; }
                }
                if (enabled)
                {
                    sample += i;
                }
            }*/

            returnval = returnval.Replace("", "");
            return returnval;
        }

        static string ParseUnderline(string line)
        {
            string returnval = line;
            bool enabled = false;
            string sample = "";

            /*foreach (char i in returnval.ToCharArray())
            {
                if (i == '')
                {
                    if (enabled) 
                    { 
                        enabled = false;
                        returnval = returnval.Replace(sample, "<span style=\"text-decoration: underline\">" + sample + "</span>");
                        sample = "";
                    }
                    if (!enabled) { enabled = true; }
                }
                if (enabled)
                {
                    sample += i;
                }
            }*/

            returnval = returnval.Replace("", "");
            return returnval;
        }
        
        static string ParseHTML(string line)
        {
            string returnval = line;
            foreach (Match i in Regex.Matches(returnval, "http://(?<httpAddress>(.*))"))
            {
                string httpAddress = i.Groups["httpAddress"].ToString().Split(' ')[0];

                // TODO: Improve code to make more of a thumbnail at the right aspect rashio
                /*if ((httpAddress.Contains(".png")) || (httpAddress.Contains(".jpg")) || (httpAddress.Contains(".gif"))) 
                {
                    string fileName = httpAddress.Split('/')[httpAddress.Split('/').GetUpperBound(0)];
                    string fullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ShionTemp\\" + fileName);
                    if (!File.Exists(fullPath))
                    {
                        WebClient x = new WebClient();
                        x.DownloadFileCompleted+=new System.ComponentModel.AsyncCompletedEventHandler(x_DownloadFileCompleted);
                        x.DownloadFileAsync(new Uri("http://" + httpAddress), fullPath);
                        returnval = returnval.Replace("http://" + httpAddress, "<a target=\"_blank\" href=\"http://" + httpAddress + "\"><img src=\"file://" + fullPath + "\" width=300 height=300></img></a>"); 
                    }
                    else
                    {
                        returnval = returnval.Replace("http://" + httpAddress, "<a target=\"_blank\" href=\"http://" + httpAddress + "\"><img src=\"file://" + fullPath + "\" width=300 height=300></img></a>");
                    }
                }
                else {*/ returnval = returnval.Replace("http://" + httpAddress, "<a target=\"_blank\" href=\"http://" + httpAddress + "\">http://" + httpAddress + "</a>"); //}
            }
            return returnval;
        }

        static void x_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            //TODO: Do Refresh of Active Window
        }

        static string ParseColors(string line)
        {
            try
            {
                string returnval = line;
                int x = 0;
                int y = 0;

                string ParseBackColor = @"\x03(?<group1>[0-9]{1,2}),(?<group2>[0-9]{1,2})";
                string ParseForeColor = @"\x03(?<group1>[0-9]{1,2})";
                string ParseColorChar = @"\x03";

                foreach (Match i in Regex.Matches(returnval, ParseBackColor))
                {
                    int group1 = Convert.ToInt32(i.Groups["number1"].ToString());
                    int group2 = Convert.ToInt32(i.Groups["number2"].ToString());

                    string resultString = null;

                    Regex regexObj = new Regex(@"\x03(?<group1>[0-9]{1,2}),(?<group2>[0-9]{1,2})");
                    resultString = regexObj.Replace(i.Value, "<span class=\"color" + group1 + "\"><span class=\"background" + group2 + "\">");

                    returnval = returnval.Replace(i.Value, resultString);
                }
                foreach (Match i in Regex.Matches(returnval, ParseForeColor))
                {
                    int group1 = Convert.ToInt32(i.Groups["group1"].ToString());

                    string resultString = null;

                    Regex regexObj = new Regex(@"\x03(?<group1>[0-9]{1,2})");
                    resultString = regexObj.Replace(i.Value, "<span class=\"color" + group1 + "\">");

                    returnval = returnval.Replace(i.Value, resultString);
                }

                return returnval;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return "";
            }
        }

        static string FindDigitInString(string str)
        {
            return System.Text.RegularExpressions.Regex.Replace(str, "[^0-9]", "");
        }
    }
}
